#!/usr/bin/perl -w

####################################################
# Copyright (c) 2002-2007 BioWare Corp.
# http://www.bigdaddymonitor.org
#
# This file is part of the BigDaddy Monitoring
# program. It is free software distributed under
# the terms of the BSD License. It is ditributed
# in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY; without event the implied
# warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# The BSD License is available from:
# http://www.opensource.org/licenses/bsd-license.php
####################################################

#===================================================================================================
# BigDaddy Common Functions
# Dups 14.04.2006 <dups@bioware.com>
#===================================================================================================

use MIME::Lite;
use Net::SMTP;


#===================================================================================================
# Daemonizes script
#===================================================================================================
sub daemonize
{

	#change to the root directory so that no NFS mounts get
	#screwed up
	chdir "/" or die "Can't chdir to /: $!\n";

	#pass the STDIN, OUT and ERR to Dev NULL
	open STDIN, '> /dev/null' or die "Can't Open devnull for inputting: $!\n";
	open STDOUT, '> /dev/null' or die "Can't open devnull for output: $!\n";
	open STDERR, '> /dev/null' or die "Can't open devnull for output: $!\n";

	#fork
	defined(my $pid = fork) or die "Could Not Fork: $!\n";
	exit if $pid;
	POSIX::setsid() or die "Could not set session ID: $!\n";
}

#===================================================================================================
# send_mail(str emailString, str messageString, $subjectString, $fromString, $mailServer)
# Sends email to email string (emails seperated by comma) with message string attached that
# is contained in ini for that level
#===================================================================================================
sub send_mail
{
	my ($emailString, $messageString, $subjectString, $fromString, $mailServer) = @_;
   
    my @email = split (/,/, $emailString);
    
    for (my $i=0; $i<scalar(@email); $i++)
    {
        my $msg = MIME::Lite->new(
            From     =>$fromString,
            To       =>$email[$i],
            Type     =>'text/plain',
            Subject  =>$subjectString,
            Data     =>$messageString
            );
        
        #Send the message
        my $message=$msg->as_string();
        
        print $message."\n";
        print $mailServer."\n";
        print $email[$i];

		my $smtpServer = Net::SMTP->new($mailServer);
		$smtpServer->mail($fromString);
		$smtpServer->to($email[$i]);
		$smtpServer->data();
		$smtpServer->datasend($message);
		$smtpServer->dataend();

		$smtpServer->quit();
    }

}

#===================================================================================================
# addzero(int num)
# Adds zero to number less than 10
#===================================================================================================
sub addzero
{
	my ($number) = @_;
	if ($number<10)
	{
		return "0".$number;
	}
	else
	{
		return $number;
	}

}

#===================================================================================================
# CheckMasterSlave()
# Returns 1 if this is a slave and master is fully functional
# Returns 2 if this is a master or if master is not functional
#===================================================================================================
sub CheckMasterSlave
{
    
    my ($bigdaddy_cfg, $sProcessName) = @_;
    
    my $sql;
    my $nReturn;

    #if in master slave configuration and this is the master, simply continue
	if ($bigdaddy_cfg->val('masterslave', 'thisinstance') eq "master")
	{
        return 2;
    }
	
    my $dbmaster = callfor_db_handle($bigdaddy_cfg->val('masterslave', 'masterdbhandle'), 0, 99);
	#Now run a query
	# if it fails at any point we just continue
	if (defined($dbmaster))
    {
        $sql = "SELECT 1 as number";
        my $result=$dbmaster->prepare( $sql ) or return 2;
        $result->execute or return 2;
	}
				
	$sql = "SELECT report FROM report WHERE ID = '".$sProcessName."'";
	my $result=$dbmaster->prepare( $sql );
	$result->execute;
			
    while (my $ref=$result->fetchrow_hashref())
    {
        my $nThresholdVal = time() - $bigdaddy_cfg->val('masterslave', 'threshold');
        if ($ref->{'report'} < $nThresholdVal)
        {
            $dbmaster->disconnect;
            return 2;
        }
        else
        {
            return 1;
            
        }
    }
}
#===================================================================================================
# CheckMultiMaster()
# Returns 1 if this other master is functional
# Returns 2 if this master should take over
#===================================================================================================

sub CheckMultiMaster
{
    my ($bigdaddy_cfg, $dbIniHandle, $this_process_name, $sID) = @_;
    
    my $nReturn;
    
    my $dbbcheck = callfor_db_handle($dbIniHandle, 0, 99);
    
    my $sql = "SELECT report, processID FROM report WHERE ID = '".$sID."'";
	my $result=$dbbcheck->prepare( $sql );
	$result->execute;
			
    while (my $ref=$result->fetchrow_hashref())
    {
        #If  that was this process, just bloody continue
        if ($ref->{'processID'} eq $this_process_name)
        {
            $nReturn = 2;
        }
        else
        {
            #If threshold has been breached
            my $nThresholdVal = time() - $bigdaddy_cfg->val('multimaster', 'threshold');
            if ($ref->{'report'} < $nThresholdVal)
            {
                $nReturn = 2;
            }
            else
            {
                $nReturn = 1;
                
            }
        }
    }
    
    $dbbcheck->disconnect();
    return $nReturn;

}

#===================================================================================================
# Write Process Info for this server
# Opens a log file with the current process time. This will allow bigdaddy check to make sure
# that the processes are all running.
#===================================================================================================
sub SetProcessTime
{
	my ($processFile) = @_;
	open (PROCESSFILE, ">$processFile") or die "Could not open process $processFile file for writing: $!";
	print PROCESSFILE time();
	close (PROCESSFILE) or die "Could not close $processFile file: $!";
}
#===================================================================================================
# trim String
#===================================================================================================
sub trim($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}


1;

